<script setup>
import {ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";
import {Plus, QuestionFilled} from "@element-plus/icons-vue";
import HostDialog from "@/views/fileDistribution/components/hostDialog.vue";

const TableData = ref([])

const groupData = ref([])
const typeData = ref([])

const alertMethodData = ref([])
const recvAlertGroupData = ref([])

const hostDialogStatus = ref(true)
const HostDialogTitle = ref("")
const HostDialogVisible = ref(false)

const hostName = ref('')

const handleSrcHostDialogValue = () => {
  HostDialogTitle.value = '选择主机'
  HostDialogVisible.value = true
}
const HandleTuple = (tuple) => {
  hostName.value = tuple.value.hostname
  form.value.host_id = tuple.value.id
};

const props = defineProps({
  taskId: {
    type: Number,
    default: -1,
    required: true
  },
  tableData: {
    type: Array,
    default: () => [],
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
})

const form = ref({
  task_id: 0,
  mon_group_id: '',
  type: '',
  name: '',
  host_id: '',
  mon_path: '',
  timeout: 5000,
  mon_freq: '',
  trigger_threshold: '',
  recv_alert_group: [],
  alert_method_list: [],
  quiet_time: '',
  remark: '',
  create_time: '',
  sort_num: 1,
})

const formRef = ref(null)

const initData = async (taskID) => {
  console.log(taskID, '----------------taskID')
  try {
    if (taskID === undefined) {
      taskID = -1
    }
    const res = await requestUtil.get('monitor_alert/group/action')
    const data = res.data
    if (data.code === 200) {
      groupData.value = data.group_msg
      typeData.value = data.type_msg
      alertMethodData.value = data.alert_method_msg
    } else {
      ElMessage.error(data.msg)
    }

    const groupRes = await requestUtil.post('monitor_alert/group/list')
    const groups = groupRes.data
    if (groups.code === 200) {
      recvAlertGroupData.value = groups.msg;
    } else {
      ElMessage.error(groups.msg)
    }

    if (taskID !== -1) {
      const res = await requestUtil.get(`monitor_alert/task/action?task_id=${taskID}`)
      const data = res.data
      if (data.code === 200) {
        form.value = data.msg[0];
        form.value.recv_alert_group = data.group;

      } else {
        ElMessage.error(data.msg)
      }

    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}


const rules = ref({
  mon_group_id: [
    {required: true, message: '监控分组不能为空'}
  ],
  type: [
    {required: true, message: '监控类型不能为空'}
  ],
  host_id: [
    {required: true, message: '监控主机不能为空'}
  ],
  name: [
    {required: true, message: '监控名称不能为空'}
  ],
  mon_path: [
    {required: true, message: '监控地址不能为空'}
  ],
  mon_freq: [
    {required: true, message: '监控频率不能为空'}
  ],
  trigger_threshold: [
    {required: true, message: '触发阈值不能为空'}
  ],
  recv_alert_group: [
    {required: true, message: '接收告警组不能为空'}
  ],
  alert_method_list: [
    {required: true, message: '告警方式不能为空'}
  ],
  quiet_time: [
    {required: true, message: '沉默时间不能为空'}
  ],
  sort_num: [
    {required: true, message: '显示顺序不能为空'}
  ],
})

const emits = defineEmits(['update:modelValue', 'initTableData', 'initGroupAndTypeData'])

const handleClose = () => {
  emits('update:modelValue', false)
  emits('initGroupAndTypeData')
  formRef.value.resetFields()
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    try {
      if (valid) {
        let add = -1
        if (props.taskId === -1) {
          add = 1
        }
        let res = await requestUtil.post(`monitor_alert/task/action?activeID=1&add=${add}`, form.value);
        let data = res.data;
        if (data.code === 200) {
          console.log(form.value.groups)
          ElMessage.success('执行成功')
          formRef.value.resetFields()
          emits('initTableData')
          handleClose()
        } else {
          ElMessage.error(data.msg)
        }
      } else {
        console.log('fail')
      }

    } catch (error) {
      console.error('Error fetching table data:', error)
      ElMessage.error('请求失败，请稍后再试')
    }
  })
}

watch(
    () => form.value.type,
    async (newVal) => {// 改为async函数
      // 先更新验证规则
      if (newVal === 1 || newVal === 2) {
        rules.value.host_id[0].required = false
      } else {
        rules.value.host_id[0].required = true
      }
    }
)

watch(
    () => props.dialogVisible,
    () => {
      hostName.value = '';
      let id = props.taskId;
      TableData.value = props.tableData;
      if (id !== -1) {
        initData(id);
      } else {
        initData(id);
        form.value = {
          task_id: 0,
          mon_group_id: '',
          type: '',
          name: '',
          host_id: '',
          mon_path: '',
          timeout: 5000,
          mon_freq: '',
          trigger_threshold: '',
          recv_alert_group: [],
          alert_method_list: [],
          quiet_time: '',
          remark: '',
          create_time: '',
          sort_num: 1,
        }
      }
    }
)


</script>

<template>
  <el-dialog
      v-if="dialogVisible"
      :model-value="dialogVisible"
      :title="dialogTitle"
      width="700px"
      style="padding: 40px;margin-top: 40px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <!--      :validate-on-rule-change="false" 是为了阻止更改rules时立即触发校验-->
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :validate-on-rule-change="false"
    >
      <el-form-item label="监控分组:" prop="mon_group_id">
        <!-- 新增 disabled 绑定 -->
        <el-select
            v-model="form.mon_group_id"
            placeholder="请选择主机分组"
            append-to-body="true"
            :disabled="props.taskId !== -1"
        >
          <el-option
              v-for="item in groupData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="监控类型:" prop="type" label-width="100px">
        <el-select
            style="width: 100%"
            v-model="form.type"
            placeholder="请选择监控类型"
            @change="() => formRef?.clearValidate()"
        >

          <el-option
              v-for="item in typeData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="监控名称:" prop="name">
        <el-input
            v-model="form.name"
            placeholder="请输入监控名称"
        />
      </el-form-item>

      <el-form-item v-if="form.type === 3 || form.type === 4" label="监控主机:" prop="host_list">
        <el-button @click="handleSrcHostDialogValue()" size="default" :icon="Plus" type="primary">
          添加主机
        </el-button>&nbsp;
        <span class="span-bottom" v-if="hostName">已选择主机：{{ hostName }}</span>
      </el-form-item>

      <el-form-item label="监控对象:" prop="mon_path">
        <template #label>
          <div style="display: flex;align-items: center;">
            <el-text>监控对象:</el-text>
            <el-tooltip raw-content
                        content="可输入进程名、域名、IP:port、自定义shell脚本<br>(自定义脚本是通过exit 退出状态码是否为0，来判断执行是否成功)"
                        placement="right">
              <el-icon>
                <QuestionFilled style="color: red"/>
              </el-icon>
            </el-tooltip>
            <el-text type="danger" style="font-size: 12px"/>
          </div>
        </template>
        <el-input
            type="textarea"
            v-model="form.mon_path"
            placeholder="请输入监控对象"
        ></el-input>
      </el-form-item>

      <el-form-item v-if="form.type === 1 || form.type === 2" label="超时时间:" prop="timeout">
        <el-input
            v-model="form.timeout"
            placeholder="请输入超时时间"
        >
          <template #append>ms</template>
        </el-input>
      </el-form-item>

      <el-form-item label="监控频率:" prop="mon_freq">
        <el-radio-group v-model="form.mon_freq">
          <el-radio label="1分钟" value="1"/>
          <el-radio label="5分钟" value="5"/>
          <el-radio label="15分钟" value="10"/>
          <el-radio label="30分钟" value="30"/>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="触发阈值:" prop="trigger_threshold">
        <el-radio-group v-model="form.trigger_threshold">
          <el-radio label="1次" value="1"/>
          <el-radio label="2次" value="2"/>
          <el-radio label="3次" value="3"/>
          <el-radio label="4次" value="4"/>
          <el-radio label="5次" value="5"/>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="接收告警组:" prop="recv_alert_group">
        <el-select
            style="width: 100%"
            multiple
            v-model="form.recv_alert_group"
            placeholder="请选择联系人分组"
        >
          <el-option
              v-for="item in recvAlertGroupData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="告警方式:" prop="alert_method_list">
        <el-checkbox-group v-model="form.alert_method_list">
          <el-checkbox
              v-for="item in alertMethodData"
              :label="item.name"
              :key="item.id"
              :value="item.id"/>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="沉默时间:" prop="quiet_time">
        <el-select
            style="width: 100%"
            v-model="form.quiet_time"
            placeholder="请选择联系人分组"
        >
          <el-option key="t5" label="5分钟" value="5"></el-option>
          <el-option key="t10" label="10分钟" value="10"></el-option>
          <el-option key="t15" label="15分钟" value="15"></el-option>
          <el-option key="t30" label="30分钟" value="30"></el-option>
          <el-option key="t60" label="60分钟" value="60"></el-option>
          <el-option key="t180" label="3小时" value="180"></el-option>
          <el-option key="t360" label="6小时" value="360"></el-option>
          <el-option key="t720" label="12小时" value="720"></el-option>
          <el-option key="t1440" label="24小时" value="1440"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="显示顺序:" prop="sort_num">
        <el-input-number v-model="form.sort_num" :min="1" label="显示顺序"/>
      </el-form-item>

      <el-form-item label="备注:" prop="remark">
        <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注"
        ></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">验证</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>

    <HostDialog v-model="HostDialogVisible"
                :dialogVisible="HostDialogVisible"
                :srcDialogStatus="hostDialogStatus"
                @sendTuple="HandleTuple"
                :dialogTitle="HostDialogTitle"></HostDialog>
  </el-dialog>
</template>

<style scoped lang="scss">
.span-bottom {
  color: var(--el-color-primary);
  display: inline-block;
  vertical-align: bottom;
  line-height: 1;
}

.space-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 14px;
}
</style>